<template>
	<view>
		<view class="list">
			<form @submit="formSubmit">
				<view class="goodslist" v-for="(gitem,gindex) in goodsList" :key="gindex">
					<view class="goodsinfo">
						<image :src="gitem.images" mode="aspectFill"></image>
						<view class="txt">
							<view class="hd">{{gitem.title}}</view>
							<view class="bd">{{gitem.spec_text}}　X {{gitem.buy_number}}</view>
						</view>
					</view>
					<view class="item">
						<text class="pingjia">购物体验：</text>
						<view class="star" v-for="n in 5" :key="n" @tap="clickStar" :data-index="gindex" :data-value="n+1">
							<text class="pingjia iconfont " :class="form_rating_list[gindex] != undefined && form_rating_list[gindex] >= n+1 ?'icon-shoucang':'icon-xing'"></text>
						</view>

					</view>

					<view class="item">
						<textarea value="" placeholder="说说您的评价" class="content" :data-index="gindex" @input="contentEvent" />
						</view>
					<view class="photo">
						<view class="imgs">
							<view class="img" v-for="(item,index) in form_images_list[gindex]" :key="index">
								<image :src="item" mode="aspectFill"></image>
								<text class="iconfont icon-shanchu" @tap="upload_delete_event" :data-index="gindex" :data-ix="index"></text>
							</view>
							<view class="addimgs" @tap="file_upload_event"  :data-index="gindex">
								<text class="iconfont icon-xiugaitupian"></text>
								<text class="txt">上传图片</text>
							</view>
						</view>
						
					</view>
				</view>
				<view class="niming">
						<label><radio :value="is_anonymous.toString()"  name="is_anonymous" :checked="is_anonymous==1" @tap="radioChange"/>匿名</label>
					<text class="radio">您写的评价会以匿名形式展示</text>
				</view>

				<button form-type="submit">提交</button>
			</form>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderId:0,
				goodsList:[],
				userInfo:[],
				is_anonymous:0,
				tempFilePaths:'',
				editor_path_type: '',
				form_rating_list: [],
				form_images_list: [],
				form_content_list: [],
			}
		},
		onLoad(params){
			let self=this;
			this.userInfo=uni.getStorageSync("gUserInfo");
			this.orderId=params.id;
			// 根据订单orderId查出，订单的中的商品信息
			let orderParam={
				data:{
					id:this.orderId
				}
			}
			let commentsUrl=this.requestUrl.comments;
			this.util.request(commentsUrl,'post',function(res){
				console.log(res);
				if(res.data.code==0 && res.data.data){
					let data=res.data.data;
					self.editor_path_type=data.editor_path_type || '',
					self.goodsList=data.data.items;
				}
			},orderParam);
		},
		methods: {
			// 点击星星
			clickStar(e){
				// 参数
				    var index = e.currentTarget.dataset.index;
				    var value = e.currentTarget.dataset.value;
				
				    // 数据初始化/赋值
				    var temp_list =JSON.parse(JSON.stringify(this.form_rating_list));
				    var length = this.goodsList.length;
				    for(var i=0; i<length; i++)
				    {
				      if (temp_list[i] == undefined)
				      {
				        temp_list[i] = 0;
				      }
				      if(index == i)
				      {
				        temp_list[i] = value;
				      }
				    }
					this.form_rating_list=temp_list;	
			},
			// 单选框更改
			radioChange(){
				if(this.is_anonymous==0){
					this.is_anonymous=1;
				}else{
					this.is_anonymous=0;
				}
			},
			// 评价内容
			contentEvent(e){
					// 参数
				    var index = e.currentTarget.dataset.index;
				    var value = e.detail.value;
				
				    // 数据初始化/赋值
				    var temp_list = this.form_content_list;
				    var length = this.goodsList.length;
				    for (var i = 0; i < length; i++) {
				      if (temp_list[i] == undefined) {
				        temp_list[i] = '';
				      }
				      if (index == i) {
				        temp_list[i] = value;
				      }
				    }
				    this.form_content_list= temp_list
			},
			// 文件上传
			file_upload_event(e) {
			    // 数据初始化
			    var index = e.currentTarget.dataset.index;
			    var temp_list = JSON.parse(JSON.stringify(this.form_images_list));
			    var length = this.goodsList.length;
			    for (var i = 0; i < length; i++) {
			      if (temp_list[i] == undefined) {
			        temp_list[i] = [];
			      }
			    }
				this.form_images_list=temp_list;
			    // 处理上传文件
			    var self = this;
			    uni.chooseImage({
			      count: 3,
			      success(res) {
			        var success = 0;
			        var fail = 0;
			        var length = res.tempFilePaths.length;
			        var count = 0;
			        self.upload_one_by_one(index, res.tempFilePaths, success, fail, count, length);
			      }
			    });
			},
			  // 采用递归的方式上传多张
			upload_one_by_one(index, img_paths, success, fail, count, length) {
			    var self = this;
			    if ((self.form_images_list[index] || null) == null || self.form_images_list[index].length < 3) {
					let filesUploadUrl=this.requestUrl.filesUpload + self.userInfo.token
			        uni.uploadFile({
			          url:filesUploadUrl,
			          filePath: img_paths[count],
			          name: 'upfile',
			          formData: {
			            action: 'uploadimage',
			            path_type: self.editor_path_type
			          },
			          success: function (res) {
			            success++;
			            if (res.statusCode == 200) {
			              var data = (typeof (res.data) == 'object') ? res.data : JSON.parse(res.data);
			              if (data.code == 0 && (data.data.url || null) != null) {
			                var list =JSON.parse(JSON.stringify(self.form_images_list));
			                if ((list[index] || null) == null)
			                {
			                  list[index] = [];
			                }
			                list[index].push(data.data.url);
							self.form_images_list=list;
			              } else {
							uni.showToast({
								title: data.msg,
								duration:1000
							});
			              }
			            }
			          },
			          fail: function (e) {
			            fail++;
			          },
			          complete: function (e) {
			            count++; // 下一张
			            if (count >= length) {
			              // 上传完毕，作一下提示
						  uni.showToast({
						  	title: '上传成功' + success +'张',
							duration:1500
						  });
			            } else {
			              // 递归调用，上传下一张
			              self.upload_one_by_one(index, img_paths, success, fail, count, length);
			            }
			          }
			        });
			    }
			},
			 // 图片删除
			  upload_delete_event(e) {
			    var index = e.currentTarget.dataset.index;
			    var ix = e.currentTarget.dataset.ix;
			    var self = this;
			    wx.showModal({
			      title: '温馨提示',
			      content: '删除后不可恢复、继续吗？',
			      success(res) {
			        if (res.confirm) {
			          var list = JSON.parse(JSON.stringify(self.form_images_list));
			          list[index].splice(ix, 1);
					  self.form_images_list=list
			        }
			      }
			    });
			  },
			formSubmit(e){
				let self=this;
				// 商品数量
				var length = this.goodsList.length;

				// 评分校验
				var count = this.form_rating_list.length;
				if (count < length)
				{
				  uni.showToast({
					  title:'请评分',
					  duration:1500
				  })
				  return false;
				}
				var max = Math.max.apply(null, this.form_rating_list);
				var min = Math.min.apply(null, this.form_rating_list);
				if (min < 1 || max > 5)
				{
					uni.showToast({
				  		title:'评分有误',
				  		duration:1500
					})
				  return false;
				}

				// 内容校验
				var count = this.form_content_list.length;
				if (count < length) {
				  uni.showToast({
				  	title:'请填写评论内容',
				  	duration:1500
				  })
				  return false;
				}
				for (var i in this.form_content_list)
				{
				  var count = this.form_content_list[i].length;
				  if (count < 6 || count > 230)
				  {
					uni.showToast({
						title:'评论字数6~23',
						duration:1500
					})
					return false;
				  }
				}
				
				// 图片校验
				if (this.form_images_list.length > 0)
				    {
				      for (var i in this.form_images_list)
				      {
				        if (this.form_images_list[i].length > 3)
				        {
						  uni.showToast({
						  	title:'图片最多3张',
						  	duration:1500
						  })
				          return false;
				        }
				      }
				}
				let form_data=[];
				form_data['goods_id'] = JSON.stringify(this.goodsList.map(function (v) { return v.goods_id }));
				form_data['id'] = this.orderId;
				form_data['is_anonymous'] = this.is_anonymous;
				form_data['rating'] = JSON.stringify(this.form_rating_list);
				form_data['content'] = JSON.stringify(this.form_content_list);
				form_data['images'] = (this.form_images_list.length > 0) ? JSON.stringify(this.form_images_list) : '';
				let params={
					data:form_data
				}
				let commentsSaveUrl=this.requestUrl.commentsSave;
				this.util.request(commentsSaveUrl,'post',function(res){
					if(res.data.code==0){
						uni.showToast({
							title:res.data.msg,
							duration:1500,
							success:function(){
								uni.redirectTo({
								    url: `/pages/order/order?state=0`
								});
							}
						})
					}
				},params)
			}
			
		}
	}
</script>

<style lang="scss" scoped>
.list{padding:30rpx;width:100%;box-sizing: border-box;display: flex;flex-direction: column;}
.goodslist{display:flex;flex-direction:column;}
.goodsinfo{display:flex;flex-direction:row;}
.goodsinfo image{width:150upx;height:150rpx;margin-right:20rpx}
.goodsinfo .txt{width:500rpx;}
.goodsinfo .txt .hd{font-size:$uni-font-size-base;color:$uni-text-color}
.goodsinfo .txt .bd{font-size:$uni-font-size-sm;color:$uni-text-color-grey;margin-top: 10px;}
.item{width:100%;padding:15rpx 0;display: flex;flex-direction: row;}
.pingjia{font-size:$uni-font-size-base + 2upx;margin-right: 15rpx;}

.icon-xing{font-size: $uni-font-size-lg + 4upx;color: $uni-text-color;}
.icon-shoucang{color: #d81e06;font-size: $uni-font-size-lg + 4upx;}
.item label{font-size: $uni-font-size-base + 2upx;}
.niming{width:100%;padding:15rpx 0;}
.radio{font-size: $uni-font-size-sm;color: $uni-text-color-grey;float: right;}
.content{border:solid 1px $uni-border-color;width:100%;padding:15rpx;box-sizing: border-box;background: $uni-bg-color-grey;}

// 上传图片
.photo{width:100%;padding:15px 0;}
.imgs{display: flex;flex-direction: row;flex-wrap: wrap;width:100%}
.img{position: relative;width:140rpx;height: 140rpx;margin:0rpx 5px 10px;border:solid 1px #999999}
.img image{width:140rpx;height: 140rpx;}
.img .icon-shanchu{background:#000000;color: #fff;position: absolute;top:-15rpx;right:0;width:30rpx;height: 30rpx;border-radius: 100%;}
.addimgs{width:140rpx;height: 140rpx;display: flex;flex-direction: column;align-items: center;border:dashed 1px  $uni-text-color-grey;border-radius: $uni-border-radius-base;justify-content: center;margin:0px 5px 10px}
.icon-xiugaitupian{font-size: 70rpx;}
.txt{font-size: $uni-font-size-base;color: $uni-text-color-grey;}

</style>
